﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;
using CCWin;
using CCWin.SkinControl;
using System.Runtime.InteropServices;
using CCWin.Win32;
using ESPlus.Application.CustomizeInfo;
using ESBasic;
using GG.Core;
using ESPlus.Rapid;
using ESBasic.ObjectManagement.Forms;
using ESPlus.Application.FileTransfering;
using ESPlus.FileTransceiver;
using ESPlus.Application.Basic;
using OMCS.Passive;
using System.Configuration;
using GGLib.NDisk.Passive;
using ESBasic.ObjectManagement.Managers;
using GGLib.Core;
using GGLib.NDisk;
using OMCS.Passive.MicroMessages;

namespace GG
{
    public partial class MainForm : CCSkinMain
    {
        private User currentUser;
        private IMultimediaManager multimediaManager = MultimediaManagerFactory.GetSingleton();
        private IRapidPassiveEngine rapidPassiveEngine;
        private GlobalUserCache globalUserCache; //缓存用户资料
        private FormManager<string, ChatForm> chatFormManager = new FormManager<string, ChatForm>();
        private FormManager<string, GroupChatForm> groupChatFormManager = new FormManager<string, GroupChatForm>();
        private ObjectManager<string, Group> groupCache = new ObjectManager<string, Group>(); //缓存组资料。建议：将所有的组信息缓存在本地的持久化文件中

        private INDiskOutter nDiskOutter; // V2.0     
        private UserInformationForm userInformationForm;//悬浮至头像时
        private Image currentHeadImage;

        private ChatListSubItem myselfChatListSubItem;

        #region Ctor ,Initialize
        public MainForm()
        {
            InitializeComponent();
            this.notifyIcon.Visible = false;
        }

        public void ShowNotifyIcon()
        {
            this.notifyIcon.Visible = true;
        }

        public void Initialize(IRapidPassiveEngine engine, ChatListSubItem.UserStatus userStatus, Image stateImage)//, Image headImage, string nickName, ChatListSubItem.UserStatus userStatus, Image stateImage)
        {           
            this.rapidPassiveEngine = engine;
            this.globalUserCache = new GlobalUserCache(this.rapidPassiveEngine);

            //从服务器加载自己的详细资料
            byte[] bUser = this.rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetUserInfo, System.Text.Encoding.UTF8.GetBytes(this.rapidPassiveEngine.CurrentUserID));
            this.currentUser = (User)GGHelper.DeserializeBytes(bUser, 0, bUser.Length);
            this.globalUserCache.Add(this.currentUser);
            this.labelSignature.Text = this.currentUser.Signature;
            if (this.currentUser.HeadImageIndex >= 0)
            {
                this.currentHeadImage = Image.FromFile("head/" + this.currentUser.HeadImageIndex.ToString() + ".png");
            }
            else
            {
                this.currentHeadImage = ESBasic.Helpers.ImageHelper.Convert(this.currentUser.HeadImage);
            }
            
            this.skinPanel_HeadImage.BackgroundImage = this.currentHeadImage;
            this.labelName.Text = this.currentUser.Name;

            this.myselfChatListSubItem = new ChatListSubItem(this.currentUser.ID, userStatus);           
            this.myselfChatListSubItem.DisplayName = this.currentUser.Name;
            this.myselfChatListSubItem.HeadImage =  this.skinPanel_HeadImage.BackgroundImage;
            this.myselfChatListSubItem.PersonalMsg = labelSignature.Text;
            this.myselfChatListSubItem.Status = userStatus;
            this.chatListBox.Items[0].SubItems.Add(this.myselfChatListSubItem);

            skinButton_State.Image = stateImage;
            skinButton_State.Tag = userStatus;
            this.notifyIcon.Text = String.Format("GG：{0}", this.rapidPassiveEngine.CurrentUserID);

            this.MaximumSize = new Size(543, Screen.GetWorkingArea(this).Height);
            this.Location = new Point(Screen.PrimaryScreen.Bounds.Width - this.Width - 20, 40);

            //文件传送
            this.rapidPassiveEngine.FileOutter.FileRequestReceived += new CbFileRequestReceived(fileOutter_FileRequestReceived);
            this.rapidPassiveEngine.FileOutter.FileResponseReceived += new CbGeneric<TransferingProject, bool>(fileOutter_FileResponseReceived);
            
            this.rapidPassiveEngine.ConnectionInterrupted += new CbGeneric(rapidPassiveEngine_ConnectionInterrupted);//预订断线事件
            this.rapidPassiveEngine.RelogonCompleted += new CbGeneric<LogonResponse>(rapidPassiveEngine_RelogonCompleted);//预订重连成功事件
            this.rapidPassiveEngine.FriendsOutter.FriendConnected += new CbGeneric<string>(FriendsOutter_FriendConnected);//预订好友上线的事件
            this.rapidPassiveEngine.FriendsOutter.FriendOffline += new CbGeneric<string>(FriendsOutter_FriendOffline);//预订好友下线的事件
            
            //群、组
            this.rapidPassiveEngine.GroupOutter.BroadcastReceived += new CbGeneric<string, string, int, byte[]>(GroupOutter_BroadcastReceived);
            this.rapidPassiveEngine.GroupOutter.GroupmateConnected += new CbGeneric<string>(GroupOutter_GroupmateConnected);
            this.rapidPassiveEngine.GroupOutter.GroupmateOffline += new CbGeneric<string>(GroupOutter_GroupmateOffline);

            //网盘访问器 V2.0
            this.nDiskOutter = new NDiskOutter(this.rapidPassiveEngine.FileOutter, this.rapidPassiveEngine.CustomizeOutter);

            /* OMCS多媒体管理器 初始化 */
            this.multimediaManager.ChannelMode = ChannelMode.P2PDisabled; //通道模型          
            this.multimediaManager.SecurityLogEnabled = false;
            this.multimediaManager.CameraDeviceIndex = SystemSettings.Singleton.WebcamIndex;
            this.multimediaManager.MicrophoneDeviceIndex = SystemSettings.Singleton.MicrophoneIndex;
            this.multimediaManager.SpeakerIndex = 0;
            this.multimediaManager.DesktopEncodeQuality = 3;
            this.multimediaManager.CameraVideoSize = new Size(640, 480); //摄像头采集的分辨率
            this.multimediaManager.Initialize(this.rapidPassiveEngine.CurrentUserID, "", ConfigurationManager.AppSettings["OmcsServerIP"], int.Parse(ConfigurationManager.AppSettings["OmcsServerPort"]));
            this.multimediaManager.MicroMessageController.MicroMessageReceived += new CbGeneric<OMCS.Passive.MicroMessages.MicroMessage>(MicroMessageController_MicroMessageReceived);//V3.6
        }              
        #endregion

        //接收到好友的语音留言时，触发此事件。 V3.6
        void MicroMessageController_MicroMessageReceived(OMCS.Passive.MicroMessages.MicroMessage msg)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<MicroMessage>(this.MicroMessageController_MicroMessageReceived), msg);
            }
            else
            {
                ChatForm form = this.GetChatForm(msg.CreatorID);
                form.OnMicroMessageReceived(msg ,false);
            }
            
        }

        #region MainForm_Load
        private void MainForm_Load(object sender, EventArgs e)
        {
            InformationForm frm = new InformationForm(this.rapidPassiveEngine.CurrentUserID, currentHeadImage);
            frm.Show();            

            //加载好友列表。如果好友数量众多，可以考虑：（1）本地缓存 （2）在后台线程中分批加载
            byte[] bFriends = this.rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetFriends, null);
            List<User> friends = (List<User>)GGHelper.DeserializeBytes(bFriends,0,bFriends.Length);
            foreach (User friend in friends)
            {
                this.globalUserCache.Add(friend);
                ChatListSubItem.UserStatus status = friend.Online ? ChatListSubItem.UserStatus.Online : ChatListSubItem.UserStatus.OffLine;
                this.AddChatListSubItem(friend, status);
            }           

            //加载组
            byte[] bMyGroups = this.rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetMyGroups, null);
            List<Group> myGroups = (List<Group>)GGHelper.DeserializeBytes(bMyGroups, 0, bMyGroups.Length);
            foreach (Group group in myGroups)
            {
                this.groupCache.Add(group.ID, group);
                ChatListSubItem subItem = new ChatListSubItem(group.ID, group.Name, string.Format("{0}人",group.Members.Count), ChatListSubItem.UserStatus.Online);
                subItem.HeadImage = this.imageList1.Images[0];
                subItem.Tag = group;
                this.chatListBox_group.Items[0].SubItems.AddAccordingToStatus(subItem);
            }

            //请求离线消息 V3.2
            this.rapidPassiveEngine.CustomizeOutter.Send(InformationTypes.GetOfflineMessage, null);

            //请求离线文件 V3.2
            this.rapidPassiveEngine.CustomizeOutter.Send(InformationTypes.GetOfflineFile, null);
        }

        private void AddChatListSubItem(User friend, ChatListSubItem.UserStatus status)
        {
            ChatListSubItem subItem = new ChatListSubItem(friend.ID, friend.Name, friend.Signature, status);
            subItem.Tag = friend;
            if (friend.HeadImageIndex >= 0)
            {
                subItem.HeadImage = Image.FromFile("head/" + friend.HeadImageIndex.ToString() + ".png");
            }
            else
            {
                subItem.HeadImage = ESBasic.Helpers.ImageHelper.Convert(friend.HeadImage);
            }
            this.chatListBox.Items[1].SubItems.AddAccordingToStatus(subItem);
        }
        #endregion

        #region 网络状态变化事件       
        #region rapidPassiveEngine_RelogonCompleted
        void rapidPassiveEngine_RelogonCompleted(LogonResponse logonResponse)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<LogonResponse>(this.rapidPassiveEngine_RelogonCompleted), logonResponse);
            }
            else
            {
                if (logonResponse.LogonResult != LogonResult.Succeed)
                {
                    return;
                }

                this.skinPanel_HeadImage.BackgroundImage = this.currentHeadImage;
                this.skinButton_State.Image = this.toolStripMenuItem20.Image;
                this.skinButton_State.Tag = this.toolStripMenuItem20.Tag;
                this.myselfChatListSubItem.Status = ChatListSubItem.UserStatus.Online;
                this.MainForm_Load(this, new EventArgs());
            }
        }       
        #endregion

        #region rapidPassiveEngine_ConnectionInterrupted
        void rapidPassiveEngine_ConnectionInterrupted()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbSimple(this.rapidPassiveEngine_ConnectionInterrupted));
            }
            else
            {
                this.skinPanel_HeadImage.BackgroundImage = ESBasic.Helpers.ImageHelper.ConvertToGrey(this.currentHeadImage);
                this.skinButton_State.Image = Properties.Resources.imoffline__2_;
                this.skinButton_State.Tag = ChatListSubItem.UserStatus.OffLine;
                this.myselfChatListSubItem.Status = ChatListSubItem.UserStatus.OffLine;
                this.chatListBox.Items[1].SubItems.Clear();    
            }
        }
        #endregion
        #endregion

        #region FriendsOutter event
        #region FriendsOutter_FriendOffline
        void FriendsOutter_FriendOffline(string friendID)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<string>(this.FriendsOutter_FriendOffline), friendID);
            }
            else
            {
                User friend = this.globalUserCache.GetUser(friendID);
                if (friend != null)
                {
                    friend.Online = false;
                }

                ChatListSubItem[] items = this.chatListBox.GetSubItemsByNicName(friendID);
                if (items == null || items.Length == 0)
                {
                    return;
                }
                items[0].Status = ChatListSubItem.UserStatus.OffLine;     
                ChatForm form = this.chatFormManager.GetForm(friendID);
                if (form != null)
                {
                    form.FriendOffline();
                }
            }
        }
        #endregion

        #region FriendsOutter_FriendConnected
        void FriendsOutter_FriendConnected(string friendID)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<string>(this.FriendsOutter_FriendConnected), friendID);
            }
            else
            {
                User friend = this.globalUserCache.GetUser(friendID);
                if (friend != null)
                {
                    friend.Online = true;
                }

                ChatListSubItem[] items = this.chatListBox.GetSubItemsByNicName(friendID);
                if (items == null || items.Length == 0)
                {
                    return;
                }

                items[0].Status = ChatListSubItem.UserStatus.Online;
                ChatForm form = this.chatFormManager.GetForm(friendID);
                if (form != null)
                {
                    form.FriendOnline();
                    return;
                }               
            }
        }
        #endregion
        #endregion

        #region GroupOutter_event
        void GroupOutter_GroupmateOffline(string userID)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<string>(this.GroupOutter_GroupmateOffline), userID);
            }
            else
            {
                User user = this.globalUserCache.GetUser(userID);
                if (user != null)
                {
                    user.Online = false;
                }

                foreach (GroupChatForm form in this.groupChatFormManager.GetAllForms())
                {
                    if (form != null)
                    {
                        form.GroupmateStateChanged(userID,false);
                        return;
                    }
                }
            }
        }

        void GroupOutter_GroupmateConnected(string userID)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<string>(this.GroupOutter_GroupmateConnected), userID);
            }
            else
            {
                User user = this.globalUserCache.GetUser(userID);
                if (user != null)
                {
                    user.Online = true;
                }

                foreach (GroupChatForm form in this.groupChatFormManager.GetAllForms())
                {
                    if (form != null)
                    {
                        form.GroupmateStateChanged(userID, true);
                        return;
                    }
                }
            }
        } 
        #endregion

        #region 文件传输
        #region //接收方收到文件发送 请求时 的 处理
        void fileOutter_FileRequestReceived(string projectID, string senderID, string projectName, ulong totalSize, ResumedProjectItem resumedFileItem, string comment)
        {
            string dir = Comment4NDisk.ParseDirectoryPath(comment);
            if (dir != null) //表明为网盘或远程磁盘
            {
                return;
            }           
           

            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbFileRequestReceived(this.fileOutter_FileRequestReceived), projectID, senderID, projectName, totalSize, resumedFileItem, comment);
            }
            else
            {
                try
                {
                    string offlineFileSenderID = Comment4OfflineFile.ParseUserID(comment);
                    bool offlineFile = (offlineFileSenderID != null);
                    if (offlineFile)
                    {
                        senderID = offlineFileSenderID;
                    }
                    ChatForm form = this.GetChatForm(senderID);
                    form.AppendSysMessage(string.Format("对方给您发送了离线文件'{0}'，大小：{1}" ,projectName ,ESBasic.Helpers.PublicHelper.GetSizeString(totalSize)));
                    form.FileRequestReceived(projectID, offlineFile);
                    form.FlashChatWindow();
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "GG");
                   
                }
            }
        }
        #endregion

        #region 发送方收到 接收方（同意或者拒绝 接收文件）的回应时的 处理
        void fileOutter_FileResponseReceived(TransferingProject project, bool agreeReceive)
        {
            if (project.Comment != null) //表示为网盘或远程磁盘
            {
                return;
            }

            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<TransferingProject, bool>(this.fileOutter_FileResponseReceived), project, agreeReceive);
            }
            else
            {
                try
                {
                    ChatForm form = this.GetChatForm(project.DestUserID);
                    form.FlashChatWindow();
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message, "GG");                    
                }
            }
        }
        #endregion
        #endregion
       
        private void chatShow_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {
            ChatListSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            string friendID = item.NicName;
            if (friendID == this.rapidPassiveEngine.CurrentUserID)
            {
                return;
            }
            
            ChatForm form = this.GetChatForm(friendID);         
            form.Show();
            form.Focus();
        }

        private ChatForm GetChatForm(string friendID)
        {
            ChatForm form = this.chatFormManager.GetForm(friendID);
            if (form == null)
            {
                ChatListSubItem[] items = this.chatListBox.GetSubItemsByNicName(friendID);
                if (items == null || items.Length == 0)
                {
                    return null;
                }
                
                //最近联系人
                if (this.chatListBox_recent.Items[0].SubItems.Count > 0 && this.chatListBox_recent.Items[0].SubItems.Contains(items[0]))
                {
                    this.chatListBox_recent.Items[0].SubItems.Remove(items[0]);
                }
                this.chatListBox_recent.Items[0].SubItems.Insert(0, items[0]);

                this.rapidPassiveEngine.P2PController.P2PConnectAsyn(friendID);//尝试P2P连接。
                form = new ChatForm(this.rapidPassiveEngine, this.multimediaManager,this.nDiskOutter, this.labelName.Text, items[0]);
                this.chatFormManager.Add(form);
                form.Show();
            }
            return form;
        }

        private GroupChatForm GetGroupChatForm(string groupID)
        {
            GroupChatForm form = this.groupChatFormManager.GetForm(groupID);
            if (form == null)
            {
                Group group = this.groupCache.Get(groupID);
                form = new GroupChatForm(this.rapidPassiveEngine, group, this.globalUserCache);
                this.groupChatFormManager.Add(form);
                form.Show();
            }
            return form;
        }

        private void chatListBox_group_DoubleClickSubItem(object sender, ChatListEventArgs e)
        {
            ChatListSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;
            string groupID = item.NicName;
            GroupChatForm form = this.GetGroupChatForm(groupID);            
            form.Show();
            form.Focus();
        }
      

        //打开QQ主菜单
        private void toolQQMenu_Click(object sender, EventArgs e)
        {
            this.skinContextMenuStrip_mainMenu.Show(skinToolStrip1, new Point(3, -2), ToolStripDropDownDirection.AboveRight);    
        }
        
        private void chatShow_MouseEnterHead(object sender, ChatListEventArgs e)
        {            
            int top = this.Top + this.chatListBox.Top + (e.MouseOnSubItem.HeadRect.Y - this.chatListBox.chatVScroll.Value);
            int left = this.Left - 279 - 5;           
            int ph = Screen.GetWorkingArea(this).Height;
           
            if (top + 181 > ph)
            {
                top = ph - 181 - 5;
            }
            
            if (left < 0)
            {
                left = this.Right + 5;
            }
           
            if (userInformationForm != null)
            {
                this.userInformationForm.Item = e.MouseOnSubItem;
                this.userInformationForm.Location = new Point(left, top);
                this.userInformationForm.Show();
            }
            else  
            {
                this.userInformationForm = new UserInformationForm(e.MouseOnSubItem, new Point(left, top));
                this.userInformationForm.Show();
            }
        }
        
        private void chatShow_MouseLeaveHead(object sender, ChatListEventArgs e)
        {
            Thread.Sleep(100);
            if (this.userInformationForm != null && !this.userInformationForm.Bounds.Contains(Cursor.Position))
            {
                this.userInformationForm.Hide();
            }
        }

        //选择状态
        private void skinButton_State_Click(object sender, EventArgs e)
        {
            this.skinContextMenuStrip_State.Show(skinButton_State, new Point(0, skinButton_State.Height), ToolStripDropDownDirection.Right);
        }

        //状态选择项
        private void Item_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem Item = (ToolStripMenuItem)sender;
            skinButton_State.Image = Item.Image;
            skinButton_State.Tag = Item.Tag;
            this.myselfChatListSubItem.Status = (ChatListSubItem.UserStatus)Convert.ToInt32(skinButton_State.Tag);

            if (this.myselfChatListSubItem.Status == ChatListSubItem.UserStatus.OffLine)
            {
                this.skinPanel_HeadImage.BackgroundImage = ESBasic.Helpers.ImageHelper.ConvertToGrey(this.currentHeadImage);
            }
            else
            {
                this.skinPanel_HeadImage.BackgroundImage = this.currentHeadImage;
            }
        } 
        
        private void notyfyIcon1_MouseDoubleClick(object sender, EventArgs e)
        {
            this.Visible = !this.Visible;

            if (this.Visible)            
            {
                this.Focus();
            }
        }

        private void toolQQShow_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.Focus();
        }

        private bool gotoExit = false;
        private void toolExit_Click(object sender, EventArgs e)
        {
            this.gotoExit = true;
            this.Close();
        }

        private void toolstripButton_mainMenu_MouseEnter(object sender, EventArgs e)
        {
            this.toolstripButton_mainMenu.Image = Properties.Resources.menu_btn_highlight;
        }

        private void toolstripButton_mainMenu_MouseLeave(object sender, EventArgs e)
        {
            this.toolstripButton_mainMenu.Image = Properties.Resources.menu_btn_normal;
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (!SystemSettings.Singleton.ExitWhenCloseMainForm && !this.gotoExit)
            {
                this.Visible = false;
                e.Cancel = true;
                return;
            }
            this.rapidPassiveEngine.Close();
            this.multimediaManager.Dispose();
        }

        //V2.0
        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            NDiskForm form = new NDiskForm(null, null, this.rapidPassiveEngine.FileOutter, this.nDiskOutter);
            form.Show();
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            this.ToAddFriend();
        }

        private void 添加好友ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            this.ToAddFriend();
        }

        private void ToAddFriend()
        {
            AddFriendForm form = new AddFriendForm(this.rapidPassiveEngine);
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.AddNewFriendItem(form.FriendID);
                ChatForm chatForm = this.GetChatForm(form.FriendID);
                chatForm.AppendSysMessage("您已经成功将对方添加为好友，可以开始对话了...");
                chatForm.Show();
                chatForm.Focus();
            }
        }

        private void AddNewFriendItem(string friendID)
        {
            byte[] bUser = this.rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetUserInfo, System.Text.Encoding.UTF8.GetBytes(friendID));
            User friend = (User)GGHelper.DeserializeBytes(bUser, 0, bUser.Length);
            ChatListSubItem.UserStatus status = friend.Online ? ChatListSubItem.UserStatus.Online : ChatListSubItem.UserStatus.OffLine;
            this.AddChatListSubItem(friend, status);
        }

        /// <summary>
        /// 被别人添加为好友
        /// </summary>       
        private void OnAddedFriend(string ownerID)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<string>(this.OnAddedFriend), ownerID);
            }
            else
            {
                this.AddNewFriendItem(ownerID);
                ChatForm chatForm = this.GetChatForm(ownerID);
                chatForm.AppendSysMessage("对方添加您为好友，可以开始对话了...");
                chatForm.Show();
                chatForm.Focus();
            }
        }

        /// <summary>
        /// 被别人添加为好友
        /// </summary>       
        private void OnRemovedFriend(string friendID)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new CbGeneric<string>(this.OnRemovedFriend), friendID);
            }
            else
            {
                ChatListSubItem[] items = this.chatListBox.GetSubItemsByNicName(friendID);
                if (items == null || items.Length == 0)
                {
                    return;
                }
                ChatListSubItem item = items[0];
                User friend = (User)item.Tag;
                item.OwnerListItem.SubItems.Remove(item);
                this.chatListBox.Invalidate();
                if (this.chatListBox_recent.Items[0].SubItems.Count > 0 && this.chatListBox_recent.Items[0].SubItems.Contains(item))
                {
                    this.chatListBox_recent.Items[0].SubItems.Remove(item);
                }
                this.chatListBox_recent.Invalidate();

                ChatForm chatForm = this.chatFormManager.GetForm(friendID);
                if (chatForm != null)
                {
                    chatForm.OnRemovedFromFriend();
                }
            }
        }

        private void toolStripSplitButton3_ButtonClick(object sender, EventArgs e)
        {
            this.chatListBox_recent.Visible = false;
            this.chatListBox.Visible = false;
            this.chatListBox_group.Visible = true;
        }

        private void toolStripSplitButton4_ButtonClick(object sender, EventArgs e)
        {
            this.chatListBox_recent.Visible = false;
            this.chatListBox.Visible = true;
            this.chatListBox_group.Visible = false;            
        }

        private void toolStripSplitButton2_ButtonClick(object sender, EventArgs e)
        {
            this.chatListBox_recent.Visible = true;
            this.chatListBox.Visible = false;
            this.chatListBox_group.Visible = false;         
        }  

        private void toolStripButton19_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            this.ToJoinGroup();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            SystemSettingForm form = new SystemSettingForm();
            form.Show();
        }

        private void 加入群ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            this.ToJoinGroup();
        }

        private void ToJoinGroup()
        {
            JoinGroupForm form = new JoinGroupForm(this.rapidPassiveEngine);
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                byte[] bGroup = this.rapidPassiveEngine.CustomizeOutter.Query(InformationTypes.GetGroup, System.Text.Encoding.UTF8.GetBytes(form.GroupID));
                Group group = (Group)GGHelper.DeserializeBytes(bGroup, 0, bGroup.Length);
                this.groupCache.Add(group.ID, group);
                ChatListSubItem subItem = new ChatListSubItem(group.ID, group.Name, string.Format("{0}人", group.Members.Count), ChatListSubItem.UserStatus.Online);
                subItem.HeadImage = this.imageList1.Images[0];
                subItem.Tag = group;
                this.chatListBox_group.Items[0].SubItems.AddAccordingToStatus(subItem);

                GroupChatForm groupChatForm = this.GetGroupChatForm(group.ID);
                groupChatForm.AppendSysMessage("您已经成功加入群，可以开始聊天了...");
                groupChatForm.Show();
                groupChatForm.Focus();
            }
        }

        private void 创建群ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            CreateGroupForm form = new CreateGroupForm(this.rapidPassiveEngine);
            if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Group group = form.Group;
                this.groupCache.Add(group.ID, group);
                ChatListSubItem subItem = new ChatListSubItem(group.ID, group.Name, string.Format("{0}人", group.Members.Count), ChatListSubItem.UserStatus.Online);
                subItem.HeadImage = this.imageList1.Images[0];
                subItem.Tag = group;
                this.chatListBox_group.Items[0].SubItems.AddAccordingToStatus(subItem);

                GroupChatForm groupChatForm = this.GetGroupChatForm(group.ID);
                groupChatForm.AppendSysMessage("您已经成功创建群...");
                groupChatForm.Show();
                groupChatForm.Focus();
            }
        }

        //退出群
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            try
            {
                Group group = (Group)this.chatListBox_group.SelectSubItem.Tag;
                if (!ESBasic.Helpers.WindowsHelper.ShowQuery(string.Format("您确定要退出群{0}({1})吗？", group.ID, group.Name)))
                {
                    return;
                }

                //SendCertainly 发送请求，并等待Ack回复
                this.rapidPassiveEngine.CustomizeOutter.SendCertainly(null, InformationTypes.QuitGroup, System.Text.Encoding.UTF8.GetBytes(group.ID));
                this.chatListBox_group.Items[0].SubItems.Remove(this.chatListBox_group.SelectSubItem);
                GroupChatForm form = this.groupChatFormManager.GetForm(group.ID);
                if (form != null)
                {
                    form.Close();
                }
                this.groupCache.Remove(group.ID);
                MessageBox.Show(string.Format("您已经退出群{0}({1})。", group.ID, group.Name));               
            }
            catch (Exception ee)
            {
                MessageBox.Show("请求超时！"+ee.Message);
            }
        }

        private void 清空会话列表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.chatListBox_recent.Items[0].SubItems.Clear();
        }

        private void 修改密码ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            UpdatePasswordForm form = new UpdatePasswordForm(this.rapidPassiveEngine);
            form.Show();
        }

        private void 删除好友ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!this.rapidPassiveEngine.Connected)
            {
                return;
            }

            try
            {
                ChatListSubItem item = this.chatListBox.SelectSubItem;
                User friend = (User)item.Tag;
                if (friend.ID == this.rapidPassiveEngine.CurrentUserID)
                {
                    return;
                }

                if (!ESBasic.Helpers.WindowsHelper.ShowQuery(string.Format("您确定要删除好友 {0}({1}) 吗？", friend.Name, friend.ID)))
                {
                    return;
                }

                //SendCertainly 发送请求，并等待Ack回复
                this.rapidPassiveEngine.CustomizeOutter.SendCertainly(null, InformationTypes.RemoveFriend, System.Text.Encoding.UTF8.GetBytes(friend.ID));
                item.OwnerListItem.SubItems.Remove(item);
                this.chatListBox.Invalidate();
                if (this.chatListBox_recent.Items[0].SubItems.Count > 0 && this.chatListBox_recent.Items[0].SubItems.Contains(item))
                {
                    this.chatListBox_recent.Items[0].SubItems.Remove(item);
                }
                this.chatListBox_recent.Invalidate();

                ChatForm chatForm = this.chatFormManager.GetForm(friend.ID);
                if (chatForm != null)
                {
                    chatForm.Close();
                }               
            }
            catch (Exception ee)
            {
                MessageBoxEx.Show("请求超时！" + ee.Message);
            }
        }

        private void toolStripMenuItem51_Click(object sender, EventArgs e)
        {

        }

         
        
    }
}